package com.example.coursedesign.ui.home;

import android.app.Application;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import com.example.coursedesign.R;
import com.example.coursedesign.ui.home.dao.MedicineDao;
import com.example.coursedesign.ui.home.dao.MedicineLikeDao;
import com.example.coursedesign.ui.home.entity.Medicine;
import com.bumptech.glide.Glide;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MedicineDetail extends AppCompatActivity {

    private TextView tvMedicineName, effectContent, mUsageContent, badReactionContent, attentionContent;
    private ImageView medicineImage;
    private ImageButton favoriteButton;
    private ExecutorService executor;
    private MedicineLikeDao medicineLikeDao;
    private TextView favoriteText;
    private boolean isFavorited = false; // 跟踪收藏状态

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.medicine_detail);

        // 初始化视图组件
        initViews();

        // 启用返回按钮
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setDisplayShowHomeEnabled(true);
        }

        // 创建线程池和Handler
        executor = Executors.newSingleThreadExecutor();

        // 获取传入的药品ID
        int medicineId = getIntent().getIntExtra("medicine_id", -1);
        if (medicineId == -1) {
            // 处理未提供药品ID的情况
            finish();
            return;
        }

        medicineLikeDao = new MedicineLikeDao(new Application()); // 初始化DAO

        // 设置收藏按钮监听器
        setFavoriteButtonClickListener(medicineId);

        // 异步从数据库获取药品详情
        loadMedicineDetails(medicineId);
    }

    private void initViews() {
        tvMedicineName = findViewById(R.id.tv_medicineName);
        effectContent = findViewById(R.id.effectContent);
        mUsageContent = findViewById(R.id.m_usageContent);
        badReactionContent = findViewById(R.id.bad_reactionContent);
        attentionContent = findViewById(R.id.attentionContent);
        medicineImage = findViewById(R.id.medicineImage);
        favoriteButton = findViewById(R.id.medicine_favoriteButton); // 假设这是收藏按钮的 ID
        favoriteText = findViewById(R.id.medicine_favoriteText);
    }

    private void setFavoriteButtonClickListener(final int medicineId) {
        final String account = "user123"; // 硬编码账户信息，实际应用中应使用登录用户的账户信息
        favoriteButton.setOnClickListener(v -> toggleFavorite(medicineId, account));
    }

    private void toggleFavorite(int medicineId, String account) {
        medicineLikeDao.isFavorited(medicineId, account, new MedicineLikeDao.OnFavoritedListener() {
            @Override
            public void onFavoritedResult(boolean currentlyFavorited) {
                // 更新 isFavorited 成员变量以反映最新状态
                isFavorited = !currentlyFavorited;
                if (currentlyFavorited) {
                    removeFavorite(medicineId, account);
                } else {
                    addFavorite(medicineId, account);
                }
            }

            @Override
            public void onError(String errorMessage) {
                // Handle error, possibly show a toast or dialog to inform the user
            }
        });
    }

    private void addFavorite(int medicineId, String account) {
        medicineLikeDao.addFavorite(medicineId, account, new MedicineLikeDao.OnOperationCompleteListener() {
            @Override
            public void onOperationComplete(boolean success) {
                if (success) {
                    isFavorited = true; // 更新为已收藏状态
                    updateFavoriteButtonUI(isFavorited);
                } else {
                    // 添加失败，可能需要通知用户
                }
            }

            @Override
            public void onError(String errorMessage) {
                // Handle error, possibly show a toast or dialog to inform the user
            }
        });
    }

    private void removeFavorite(int medicineId, String account) {
        medicineLikeDao.removeFavorite(medicineId, account, new MedicineLikeDao.OnOperationCompleteListener() {
            @Override
            public void onOperationComplete(boolean success) {
                if (success) {
                    isFavorited = false; // 更新为未收藏状态
                    updateFavoriteButtonUI(isFavorited);
                } else {
                    // 删除失败，可能需要通知用户
                }
            }

            @Override
            public void onError(String errorMessage) {
                // Handle error, possibly show a toast or dialog to inform the user
            }
        });
    }

    private void updateFavoriteButtonUI(boolean isFavorited) {
        runOnUiThread(() -> {
            if (isFavorited) {
                favoriteButton.setImageResource(R.drawable.ic_like_filled); // 已收藏图标
                favoriteText.setText("已收藏");
            } else {
                favoriteButton.setImageResource(R.drawable.ic_favorite); // 未收藏图标
                favoriteText.setText("收藏");
            }
        });
    }

    private void loadMedicineDetails(int medicineId) {
        executor.execute(() -> {
            MedicineDao medicineDao = new MedicineDao();
            Medicine medicine = medicineDao.getMedicineById(medicineId);

            // 更新UI必须在主线程中进行
            runOnUiThread(() -> updateUI(medicine));
        });
    }

    private void updateUI(final Medicine medicine) {
        if (medicine != null) {
            tvMedicineName.setText(medicine.getName());
            effectContent.setText(medicine.getEffect());
            mUsageContent.setText(medicine.getM_usage());
            badReactionContent.setText(medicine.getBad_reaction());
            attentionContent.setText(medicine.getAttention());

            // 加载图片（假设图片路径存储为URL）
            Glide.with(this).load(medicine.getImage()).into(medicineImage);

            // 检查并设置初始收藏状态
            checkAndSetInitialFavoriteState(medicine.getId(), "user123");
        } else {
            // 处理找不到药品的情况
            finish();
        }
    }

    private void checkAndSetInitialFavoriteState(int medicineId, String account) {
        medicineLikeDao.isFavorited(medicineId, account, new MedicineLikeDao.OnFavoritedListener() {
            @Override
            public void onFavoritedResult(boolean currentlyFavorited) {
                isFavorited = currentlyFavorited;
                updateFavoriteButtonUI(isFavorited);
            }

            @Override
            public void onError(String errorMessage) {
                // Handle error, possibly show a toast or dialog to inform the user
            }
        });
    }

    @Override
    public boolean onSupportNavigateUp() {
        setResult(AppCompatActivity.RESULT_OK); // 设置返回结果
        finish(); // 结束当前活动并返回上一个活动
        return true;
    }

    @Override
    public void onBackPressed() {
        setResult(AppCompatActivity.RESULT_OK); // 设置返回结果
        super.onBackPressed(); // 返回上一个 Activity
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 关闭线程池
        if (executor != null && !executor.isShutdown()) {
            executor.shutdown();
        }
    }
}